package com.why.zing.email.service.impl;


import com.why.zing.email.entity.EmailEntity;
import com.why.zing.email.service.MailService;
import freemarker.template.Configuration;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.io.IOException;


@Slf4j
@Service
public class MailServiceImpl implements MailService {

    @Autowired
    private JavaMailSender javaMailSender;

    @Value("${zing.mail.from}")
    private String sender;


    /**
     * 发送简单邮件
     *
     * @param emailEntity 邮件内容信息
     */
    @Override
    public void sendSimpleMail(EmailEntity emailEntity) {
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        mailMessage.setFrom(sender);
        mailMessage.setTo(emailEntity.getTo());
        mailMessage.setSubject(emailEntity.getSubject());
        mailMessage.setText(emailEntity.getContent());
        javaMailSender.send(mailMessage);
    }

    /**
     * 发送
     *
     * @param emailEntity 邮件内容信息
     */
    @Override
    public void sendHtmlMail(EmailEntity emailEntity) throws MessagingException {
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();

        //是否发送的邮件是富文本（附件，图片，html等）
        MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true);

        messageHelper.setFrom(sender);
        messageHelper.setTo(emailEntity.getTo());

        messageHelper.setSubject(emailEntity.getSubject());
        //重点，默认为false，显示原始html代码，无效果
        messageHelper.setText(emailEntity.getContent(), true);

        if (emailEntity.getAttachmentMap() != null) {
            emailEntity.getAttachmentMap().entrySet().forEach(entrySet -> {
                try {
                    String filePath = entrySet.getValue();
                    File file = new File(filePath);
                    if (file.exists()) {
                        String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
                        messageHelper.addAttachment(fileName, new FileSystemResource(file));
                    }
                } catch (MessagingException e) {
                    log.error("sendHtmlMail add attachment fail", e);
                }
            });
        }
        javaMailSender.send(mimeMessage);
    }

    @Override
    public void sendTemplateMail(EmailEntity emailEntity) throws MessagingException, IOException, TemplateException {
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
        helper.setFrom(sender);
        helper.setTo(emailEntity.getTo());
        Configuration configuration = new Configuration(Configuration.VERSION_2_3_28);
        configuration.setClassForTemplateLoading(this.getClass(), "/freemarker");
        String html = FreeMarkerTemplateUtils.processTemplateIntoString(configuration.getTemplate("mail.ftl"), emailEntity.getKvMap());
        helper.setSubject(emailEntity.getSubject());
        //重点，默认为false，显示原始html代码，无效果
        helper.setText(html, true);
        javaMailSender.send(mimeMessage);
    }
}
